"""
聊天系统数据库模型
"""
from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey, Text, Enum as SQLEnum
from sqlalchemy.orm import relationship
from Models.login.models import Base
from datetime import datetime
import enum


class MessageType(str, enum.Enum):
    """消息类型枚举"""
    TEXT = "text"  # 文本消息
    IMAGE = "image"  # 图片消息
    SYSTEM = "system"  # 系统消息


class ChatRoom(Base):
    """聊天房间表"""
    __tablename__ = "chat_rooms"
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    room_id = Column(String(100), unique=True, nullable=False, index=True, comment="房间号")
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True, comment="用户ID")
    kefu_id = Column(Integer, ForeignKey("users.id"), nullable=True, index=True, comment="客服ID")
    merchant_id = Column(Integer, ForeignKey("users.id"), nullable=True, index=True, comment="商家ID")
    room_type = Column(String(20), default="kefu", comment="房间类型: kefu(客服)/merchant(商户)")
    attraction_id = Column(Integer, ForeignKey("attractions.id"), nullable=True, index=True, comment="关联景点ID")
    order_id = Column(Integer, ForeignKey("orders.id"), nullable=True, index=True, comment="关联订单ID")
    is_active = Column(Boolean, default=True, comment="是否激活")
    created_at = Column(DateTime, default=datetime.now, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
    
    # 关系映射
    messages = relationship("ChatMessage", back_populates="room", cascade="all, delete-orphan")
    
    def __repr__(self):
        return f"<ChatRoom(id={self.id}, room_id={self.room_id}, user_id={self.user_id}, kefu_id={self.kefu_id}, merchant_id={self.merchant_id})>"


class ChatMessage(Base):
    """聊天消息表"""
    __tablename__ = "chat_messages"
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    room_id = Column(String(100), ForeignKey("chat_rooms.room_id"), nullable=False, index=True, comment="房间号")
    sender_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True, comment="发送者ID")
    sender_type = Column(String(20), nullable=False, comment="发送者类型: user/kefu/merchant")
    message_type = Column(SQLEnum(MessageType), default=MessageType.TEXT, comment="消息类型")
    content = Column(Text, nullable=False, comment="消息内容")
    created_at = Column(DateTime, default=datetime.now, index=True, comment="创建时间")
    
    # 关系映射
    room = relationship("ChatRoom", back_populates="messages")
    
    def __repr__(self):
        return f"<ChatMessage(id={self.id}, room_id={self.room_id}, sender_id={self.sender_id}, content={self.content[:20]}...)>"

